<template>
  <div>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    <el-upload
      class="avatar-uploader"
      action="http://127.0.0.1:3000/user/upload"
      :show-file-list="false"
      :headers="headers"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
  <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
    </el-upload>
  </div>
</template>
<script>
export default {
  data() {
    return {
      imageUrl: "",
      headers:{}
    };
  },
  created() {
  },
  methods: {
    // 手动上传
    submitUpload(){
      console.log("上传");
    },
    handleAvatarSuccess(res, file) {
      this.$message.success("上传头像成功");
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(file);
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>